package com.juzipi.demo.jdbc;

/*
练习:
    通过键盘录入用户密码判断用户是否登录成功
 */

import com.juzipi.demo.utils.JDBCUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JdbcLoginPractice {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("用户名");
        String name = scanner.nextLine();
        System.out.println("密码");
        String pwd = scanner.nextLine();
        //调用方法
        boolean login = login(name, pwd);
        //判断结果
        if (login){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }


    }

    /**
     * 登陆方法，使用 PrepareStatement 实现
     */
    public static boolean login(String name,String pwd){
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(pwd)){
            return false;
        }

        Connection connection = null;
//        Statement statement = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //获取链接
            connection = JDBCUtils.getConnection();
            //定义sql
//            String sql = "select * from user where name = '"+name+"' and pwd = '"+pwd+"'";
            String sql = "select * from user where name = ? and pwd = ?";
            //获取执行sql对象
//            statement = connection.createStatement();
            preparedStatement = connection.prepareStatement(sql);
//            //执行查询
//            resultSet = preparedStatement.executeQuery(sql);

            //给 ? 赋值
            preparedStatement.setString(1,name);
            preparedStatement.setString(2,pwd);

            //执行的时候不再需要传参
            resultSet = preparedStatement.executeQuery();

            //有下一行就返回true
            return resultSet.next();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(resultSet,preparedStatement,connection);
        }

        return false;
    }






}
